package com.example.demo.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohei.crm.common.exception.XiaoheiException;
import com.xiaohei.crm.common.result.Result;
import com.xiaohei.crm.dao.*;
import com.xiaohei.crm.mapper.CustomerMapper;
import com.xiaohei.crm.mapper.OrdersMapper;
import com.xiaohei.crm.mapper.RegionMapper;
import com.xiaohei.crm.mapper.UserMapper;
import com.xiaohei.crm.service.CustomerService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.xiaohei.crm.common.RedisEnums.CUSTOMER_REGISTRY_KEY;
import static com.xiaohei.crm.common.result.ResultCodeEnum.DATA_ERROR;


@Service
@RequiredArgsConstructor
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    private final CustomerMapper customerMapper;
    private final OrdersMapper ordersMapper;
    private final StringRedisTemplate stringRedisTemplate;

    private final RegionMapper regionMapper;
    private final UserMapper userMapper;
    @Override
    public Result<IPage> findByPage(Integer pageIndex, Integer pageSize, String customerName, String attribution, String accountManager) {
        Page<Customer> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<Customer> eq = Wrappers.lambdaQuery(Customer.class).eq(Customer::getDelFlag, 0);

        if (customerName != null) {
            eq.like(Customer::getCustomerName, customerName);
        }

        if(attribution != null){
            List<Long> ids = new ArrayList<>();
            for (Region region : regionMapper.selectList(Wrappers.lambdaQuery(Region.class).like(Region::getArea, attribution))) {
                ids.add(region.getId());
            }
            if (ids.size() != 0){
                eq.in(Customer::getAttribution, ids);
            }else {
                eq.in(Customer::getAttribution, -1);
            }
        }

        if(accountManager != null){
            List<Long> ids = new ArrayList<>();
            for (User user: userMapper.selectList(Wrappers.lambdaQuery(User.class).like(User::getName, accountManager))) {
                ids.add(user.getId());
            }
            if (ids.size() != 0){
                eq.in(Customer::getAccountManager, ids);
            }else {
                eq.in(Customer::getAccountManager, -1);
            }
        }


        Page<Customer> materialPage = customerMapper.selectPage(page,eq);
        for (Customer customer : materialPage.getRecords()) {
            Region region = regionMapper.selectById(customer.getAttribution());
            if(region!=null){
                customer.setAttributionName(region.getArea());
            }
            User user = userMapper.selectById(customer.getAccountManager());
            if (user != null) {
                customer.setAccountManagerName(user.getUsername());
            }
        }

        return Result.ok(materialPage);
    }

    @Override
    public void saveCustomer(Customer customer) {
        String s = stringRedisTemplate.opsForValue().get(CUSTOMER_REGISTRY_KEY + customer.getId());
        if(!StrUtil.isEmpty(s)){
            throw new XiaoheiException(DATA_ERROR);
        }

        int isInsert = baseMapper.insert(customer);
        if(isInsert < 1){
            throw new XiaoheiException(DATA_ERROR);
        }

        stringRedisTemplate.opsForValue()
                .set(CUSTOMER_REGISTRY_KEY + customer.getId(),customer.getId().toString());
    }

    @Override
    public void updateByCustomerId(Customer customer) {
        String s = stringRedisTemplate.opsForValue().get(CUSTOMER_REGISTRY_KEY + customer.getId());
        if(StrUtil.isEmpty(s)){
            throw new XiaoheiException(DATA_ERROR);
        }

        LambdaQueryWrapper<Customer> eq =
                Wrappers.lambdaQuery(Customer.class).eq(Customer::getId, customer.getId());
        baseMapper.update(customer,eq);
    }

    @Override
    public void removeByCustomerName(String id) {
        String s = stringRedisTemplate.opsForValue().get(CUSTOMER_REGISTRY_KEY + id);
        if(StrUtil.isEmpty(s)){
            throw new XiaoheiException(DATA_ERROR);
        }

        //校验对应的订单逻辑
        LambdaQueryWrapper<Orders> eq =
                Wrappers.lambdaQuery(Orders.class).eq(Orders::getDelFlag, 0).eq(Orders::getCustomerId, id);
        List<Orders> orders = ordersMapper.selectList(eq);
        if(!CollectionUtil.isEmpty(orders)){//订单不为空说明订单表中有和此要删除用户关联的订单  此时不能删除客户
            throw new XiaoheiException(DATA_ERROR);
        }

        LambdaUpdateWrapper<Customer> updateWrapper =
                Wrappers.lambdaUpdate(Customer.class).eq(Customer::getId,id);
        Customer customer = Customer.builder().delFlag(1).build();
        int update = baseMapper.update(customer, updateWrapper);
        if(update < 1){
            throw new XiaoheiException(DATA_ERROR);
        }

        stringRedisTemplate.delete(CUSTOMER_REGISTRY_KEY + id);
    }

}
